class Databasem:
    username = "aazz"
    age = 99
    sex = "m"
    classid = " NOCLASS"
    dhost = 'localhost'
    duser = 'root'
    dpassword ='123456'
    ddatabase = 'mydemo'
    dcharset = "utf8"

    def insertsql(self, dhost, duser, dpassword, ddatabase, charset):
        import pymysql
        conn = pymysql.connect(host=self.dhost, user=self.duser, password=self.dpassword, database=self.ddatabase, charset=self.dcharset)
        # 得到一个可以执行SQL语句的光标对象
        cursor = conn.cursor()
        sql = "INSERT INTO stu(name, age, sex, classid) VALUES (%s, %s,%s, %s);"

        try:
            # 执行SQL语句
            cursor.execute(sql, [self.username, self.age, self.sex, self.classid])
            # 提交事务
            conn.commit()
        except Exception as e:
            # 有异常，回滚事务
            conn.rollback()
        cursor.close()
        conn.close()

m = Databasem()

m.insertsql()

